package com.example.springbootvuetest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootvuetest.entity.Favorite;
import com.example.springbootvuetest.entity.IdleItem;
import com.example.springbootvuetest.mapper.FavoriteMapper;
import com.example.springbootvuetest.mapper.IdleItemMapper;
import com.example.springbootvuetest.service.IFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author shuoye
 * @since 2023-03-14
 */
@Service

public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private IdleItemMapper idleItemMapper;

    /**
     * 查询一个用户的所有收藏
     * 关联查询，没有用join，通过where in查询关联的闲置信息
     *
     * @param userId
     * @return
     */
    public List<Favorite> getAllFavorite(Integer userId) {
        QueryWrapper<Favorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).orderByDesc("create_time");
        List<Favorite> list = favoriteMapper.selectList(queryWrapper);
        if (list.size() > 0) {
            List<Integer> idleIdList = new ArrayList<>();
            for (Favorite i : list) {
                idleIdList.add(i.getIdleId());
            }
            List<IdleItem> idleItemModelList = idleItemMapper.selectBatchIds(idleIdList);
            Map<Integer, IdleItem> map = new HashMap<>();
            for (IdleItem idle : idleItemModelList) {
                map.put(idle.getId(), idle);
            }
            for (Favorite i : list) {
                i.setIdleItem(map.get(i.getIdleId()));
            }
        }
        return list;
    }
}
